import { deleteCategory, queryCategoryList } from "@/api/content/category";
import { useState, useCallback, useEffect } from "react";
import { Category } from "../../../../types/content/category";
import { message } from "antd";
import { deleteFileInf } from "@/utils/deleteFileInf";

export const useCategoryTable = () => {
  const [messageApi] = message.useMessage();
  const [loading, setLoading] = useState(false);
  const [searchForm, setSearchForm] = useState<Category.Query>({
    name: "",
    status: "",
    createBy: "",
  });
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  const [tableData, setTableData] = useState<Category.Row[]>([]);
  /**
   * 获取标签列表
   */
  const getCategoryList = useCallback(async () => {
    setLoading(true);
    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...searchForm,
    };
    const res = await queryCategoryList(params);
    setLoading(false);
    if (res.code === 200) {
      setTableData(res.data.rows || []);
      setPagination({
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        total: res.data.total,
      });
    }
  }, [pagination.pageNo, pagination.pageSize, searchForm]);

    /**
   * 删除文章
   * @param id 
   */
    const removeCategory = async (row: Category.Row) => {
      setLoading(true)
      const res = await deleteCategory({
        ids: [row.id]
      })
      setLoading(false)
      if (res.code === 200) {
        messageApi.success('删除成功')
        row.picture && deleteFileInf(row.picture)
        if (tableData.length === 1) {
          setPagination({
            pageNo: Math.max(1, pagination.pageNo - 1),
            pageSize: pagination.pageSize,
            total: pagination.total
          })
        } else {
          getCategoryList()
        }
      }
    }
  useEffect(() => {
    getCategoryList();
  }, [getCategoryList, searchForm]);
  return {
    setPagination,
    pagination,
    setSearchForm,
    tableData,
    removeCategory,
    loading,
    getCategoryList
  }
}